﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MoetutuServer.Helper
{
    class WebHelper
    {/// <summary>
    /// 同步获取html代码
    /// </summary>
    /// <param name="Url"></param>
    /// <returns></returns>
        public static string HttpGet(String Url) {

            String HtmlCode = "";

            using (WebClient webClient = new WebClient())
            {
                

                try
                {
                    webClient.Headers.Add("User-Agent", StaticValue.UserAgent);
                    webClient.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
                    HtmlCode = new StreamReader(webClient.OpenRead(Url)).ReadToEnd();
                }
                catch (Exception ex)
                {

                    PrintLog.Log(ex);
                }
            }
            return HtmlCode;
        }
        /// <summary>
        /// 获取301转移状态码，侦测资源是否发生了转移
        /// </summary>
        /// <param name="Link"></param>
        /// <returns></returns>
        public static bool GetLinkMove(String Link)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(Link);
            httpReq.AllowAutoRedirect = false;//禁止自动重定向
            try
            {
                using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
                {
                    Console.WriteLine("Code" + httpRes.StatusCode.ToString());

                    switch (httpRes.StatusCode)
                    {
                        case HttpStatusCode.Moved:
                            Console.WriteLine("301转移");
                            return true;
                        case HttpStatusCode.Found:
                            Console.WriteLine("302转移");
                            return true;
                        case HttpStatusCode.NotFound:
                            Console.WriteLine("404转移");
                            return true;

                    }


                }
            }
            catch (Exception ex)
            {
                string link = ex.Message;
                Console.WriteLine(ex.Message);
                if (link.IndexOf("404") > 0)
                    return true;


            }
            return false;
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public static String FileDownload(String FileUrl) {
            String Filename = StaticValue.ImgTemp1 + Path.GetFileName(FileUrl);
            if (Filename.Length > 200)
                Filename = StaticValue.ImgTemp1 + DateTime.Now.ToFileTime().ToString() + ".jpg";
            using (WebClient DownloadWebClient = new WebClient())
            {

                DownloadWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
              
                //注意，referer这里写死了文件名获取的方法，这里不应该写死的，如需更改请务必注意

                try
                {
                    DownloadWebClient.Headers.Add("Referer", new Uri(FileUrl).Host);
                    DownloadWebClient.DownloadFile(new Uri(FileUrl), Filename);
                }
                catch (Exception ex)
                {
                    PrintLog.Log(ex);
                    Filename = "";
                }



            }
            return Filename;

        }
    
        /// <summary>
        /// 同步获取html代码
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string HttpGet(String Url, WebHeaderCollection webHeaderCollection)
        {
       

            String HtmlCode = "";

            using (WebClient webClient = new WebClient())
            {

                try
                {
                    webClient.Headers = webHeaderCollection;
                    HtmlCode = new StreamReader(webClient.OpenRead(Url)).ReadToEnd();
                }
                catch (Exception ex)
                {

                    PrintLog.Log(ex);
                }
            }
            return HtmlCode;
        }


        /// <summary>
        /// 获取http响应状态码的类，需要连接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool GetStatusCode(String url)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Referer = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + Path.GetFileNameWithoutExtension(url);
            httpReq.Host = new Uri(url).Host;
            httpReq.AllowAutoRedirect = true;//这里很重要，如果你跟随和不跟随重定向得到的结果不同，由于我项目需要跟随重定向，故已经跟随。如果不需要请改为false
            httpReq.UserAgent = StaticValue.UserAgent;
       
            try
            {
                using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
                {
                    Console.WriteLine("0---"+httpRes.StatusCode);
                    if (httpRes.StatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine(httpRes.StatusCode);
                  
                        return true;
                    }

                    Console.WriteLine("StatusCode" + httpRes.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine (ex.Message);
                ///404 403之类的错误会在这里出现
            }
            return false;
        }
    }
}
